package com.example.demo.web;

import com.example.demo.util.AjaxPostResponse;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import java.nio.charset.Charset;

/**
 * <h4>功能:【控制器基类】【创建人：QIAOLIANG】</h4>
 *
 * @时间:2018/6/4 0004 15:08
 * @备注:<h4>用于处理post请求返回</h4>
 */
public class BaseController {
    /**

     * 返回JSON格式的响应内容。

     * @param result 响应内容

     */
    protected ResponseEntity<AjaxPostResponse> okResponse(Object result) {
        MediaType mediaType = new MediaType("application", "json", Charset.forName("UTF-8"));
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(mediaType);

        AjaxPostResponse resp = new AjaxPostResponse(result);
        return new ResponseEntity<AjaxPostResponse>(resp, headers, HttpStatus.OK);
    }

    /**

     * 返回JSON格式的响应内容（处理时发生错误的情况）。

     * @param errorMsg 错误提示信息

     */
    protected ResponseEntity<AjaxPostResponse> errorResponse(String errorMsg) {
        MediaType mediaType = new MediaType("application", "json", Charset.forName("UTF-8"));
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(mediaType);

        AjaxPostResponse resp = AjaxPostResponse.fail(errorMsg);
        return new ResponseEntity<AjaxPostResponse>(resp, headers, HttpStatus.OK);
    }

}